using Godot;
using System;
using System.Collections.Generic;
using System.Linq;

public partial class NInventory : Panel
{
	[Export] public int mMoney = 99;
	List<NItem> mItems = new List<NItem>();
	GridContainer mItemsContainer;
	bool mMouseDrag = false;
	Vector2 mDragPos = Vector2.Zero;
	Vector2 mOriPos = Vector2.Zero;
	Label mMoneyLable;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		AddToGroup(nameof(NInventory));
		mItemsContainer = GetNodeOrNull<GridContainer>("TabContainer/物品1/GridContainer");
		GuiInput += (e) => _onGUI(e);
		mMoneyLable = GetNode<Label>("Label2");
	}

	void _onGUI(InputEvent ie)
	{
		if (ie is InputEventMouseButton mb)
		{
			if (mb.ButtonIndex == MouseButton.Left)
			{
				mMouseDrag = mb.Pressed;
				if (mb.Pressed)
				{
					mDragPos = GetGlobalMousePosition();
					mOriPos = GlobalPosition;
				}
			}
		}
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		mMoneyLable.Text = mMoney.ToString();
		if (mMouseDrag)
		{
			Vector2 difPos = GetGlobalMousePosition() - mDragPos;
			GlobalPosition = mOriPos + difPos;
		}
	}

	public bool pickItem(CItem item)
	{
		//获取第一个空的面板
		int pos = _getFirstEmptyPos();
		if (pos == -1)
			return false;

		NInventoryPanel p = mItemsContainer.GetChildOrNull<NInventoryPanel>(pos);
		//动态生成NItem 实例化场景 代码
		NItem nItem = CHelp.loadScene("res://item/NItem.tscn") as NItem;
		if (nItem != null)
		{
			nItem.mItem = item;
			//这一帧的idle时间去调用目标函数，也就是末尾处
			CallDeferred("_addItem", p, nItem);
			// p.AddChild(nItem);
			Visible = true;
			return true;
		}

		return false;
	}

	void _addItem(NInventoryPanel p, NItem item)
	{
		p.AddChild(item);
	}

	int _getFirstEmptyPos()
	{
		int i = -1;
		foreach (NInventoryPanel p in mItemsContainer.GetChildren())
		{
			i++;
			NItem item = p.Item;
			if (item == null)
			{
				return i;
			}
		}
		return -1;
	}

	void _on_link_button_2_pressed()
	{
		Visible = false;
	}

	void _on_tab_container_tab_selected(int tabIndex)
	{
		//切换tab页
		if (GetTree().GetFirstNodeInGroup(NItem.CUR_SEL_ITEM) is NItem item)
		{
			//先保存父节点
			item.GetParent().AddToGroup(NInventoryPanel.CUR_SEL_PANEL);
			//重置父节点
			item.Reparent(this);
		}
	}

	void _on_link_button_pressed()
	{
		_orderItems();
	}

	void _orderItems()
	{
		mItems.Clear();
		foreach (NInventoryPanel p in mItemsContainer.GetChildren())
		{
			NItem item = p.Item;
			if (item != null)
			{
				mItems.Add(item);
				//分离物品和其父节点
				item.GetParent().RemoveChild(item);
			}
		}
		//整理
		mItems = mItems.OrderBy(i => i.mItem.mName).ToList();
		//放回背包
		int i = 0;
		foreach (NItem item in mItems)
		{
			NInventoryPanel p = mItemsContainer.GetChild<NInventoryPanel>(i);
			p.AddChild(item);
			item.Position = p.Size / 2;
			i++;
		}
	}
}
